package com.three.crm.page.common;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapException;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearchV2;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.three.crm.R;
import com.three.crm.adapter.CompanyListAdapter;
import com.three.crm.adapter.LocationAdapter;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.CompanyBean;
import com.three.crm.constant.AppConstant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 搜索位置
 * created by lqd on 2024-01-07.
 */
public class SearchLocationActivity extends BaseActivity implements AMapLocationListener, LocationSource, PoiSearch.OnPoiSearchListener,EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private TextView tvTitle,tvSearch,tvLoading;
    private EditText etInput;
    private RecyclerView recyclerView;
    private View mLoadingView;
    private ImageView ivState;
    private ProgressBar progressBar;
    private LocationAdapter adapter;

    private MapView mMapView = null;
    private AMap aMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption = null;
    private MyLocationStyle myLocationStyle = new MyLocationStyle();
    //位置更改监听
    private LocationSource.OnLocationChangedListener mListener;
    public static final int RC_PERMISSES = 1; // requestCode
    private static String BACK_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION";
    public final static String[] PERMISSES = {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION};
    private boolean hasPermiss = false;
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private int currentPage = 0;// 当前页面，从0开始计数

    private TextView tvResult;

    @Override
    protected void initParms(Bundle bundle) {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_search_location;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        initLocation();
        tvTitle = $(R.id.tv_title);
        tvTitle.setText("搜索位置");

        tvResult = $(R.id.tv_result);
        tvSearch = $(R.id.tv_search);
        etInput = $(R.id.et_input);
        mMapView = $(R.id.map);
        mMapView.onCreate(savedInstanceState);
        aMap = mMapView.getMap();
        initMap();
        mLoadingView = LayoutInflater.from(this).inflate(R.layout.loading_view,null);
        ivState = mLoadingView.findViewById(R.id.iv_state);
        tvLoading = mLoadingView.findViewById(R.id.tv_loading);
        progressBar = mLoadingView.findViewById(R.id.progressBar);

        recyclerView = $(R.id.recycleview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new LocationAdapter();
        recyclerView.setAdapter(adapter);
        onCheckPermission();
    }

    private void onCheckPermission() {
        if (EasyPermissions.hasPermissions(this,PERMISSES)){
            hasPermiss = true;
            startLocation();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name) + "需要使用定位等权限，您是否同意?",
                    RC_PERMISSES, PERMISSES);
        }
    }

    private void startLocation() {
        if (hasPermiss && mLocationClient != null && mMapView != null) {
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    private void initMap() {
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(getLayoutInflater().inflate(R.layout.layout_marker,null)));
        // 自定义精度范围的圆形边框颜色  都为0则透明
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度  0 无宽度
        myLocationStyle.strokeWidth(0);
        // 设置圆形的填充颜色  都为0则透明
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        //设置最小缩放等级为16 ，缩放级别范围为[3, 20]
        aMap.setMinZoomLevel(12);
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle);
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
    }

    private void initLocation() {
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mLocationClient != null) {
            //设置定位回调监听
            mLocationClient.setLocationListener(this);
            //初始化AMapLocationClientOption对象
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //获取最近3s内精度最高的一次定位结果：
            //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
            mLocationOption.setOnceLocationLatest(true);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
            //关闭缓存机制，高精度定位会产生缓存。
            mLocationOption.setLocationCacheEnable(false);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
        }
    }

    @Override
    protected void setListener() {
        $(R.id.iv_left).setOnClickListener(this);
        $(R.id.tv_search).setOnClickListener(this);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                CompanyBean bean = (CompanyBean) baseQuickAdapter.getItem(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putParcelable(AppConstant.EXTRAS_BEAN,bean);
                intent.putExtras(bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
            case R.id.tv_search:
                onSearch();
                break;
        }
    }

    private void onSearch() {
        String inputText = etInput.getText().toString();
        if (TextUtils.isEmpty(inputText)) {
            showToast("请输入关键字搜索");
            return;
        }
        adapter.getData().clear();
        query = new PoiSearch.Query(inputText,"","");
        query.setPageSize(20);
        query.setPageNum(currentPage);
        try {
            poiSearch = new PoiSearch(this,query);
            poiSearch.setOnPoiSearchListener(this);
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        } catch (com.amap.api.services.core.AMapException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initData(Context mContext) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                Log.i("TAG","Latitude="+aMapLocation.getCity());
               // tvLocation.setText("当前位置：" + aMapLocation.getCity() + aMapLocation.getAddress());
                //停止定位后，本地定位服务并不会被销毁
                mLocationClient.stopLocation();
                if (mListener != null) {
                    mListener.onLocationChanged(aMapLocation);
                }
//                onUploadLocation(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationClient != null) {
            mLocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
//        if (mMapView != null) {
//            mMapView.onSaveInstanceState(outState);
//        }
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        mMapView.onResume();
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        mMapView.onPause();
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        mMapView.onDestroy();
//        mListener = null;
//        mMapView = null;
//        mLocationClient = null;
//    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int rcode) {
        if (rcode == 1000) {
            List<PoiItem> poiItemList = poiResult.getPois();
            List<SuggestionCity> suggestionCityList = poiResult.getSearchSuggestionCitys();
            String sugs = "";
            if (suggestionCityList != null && suggestionCityList.size() > 0) {
                for (int i = 0; i < suggestionCityList.size(); i++) {
                    SuggestionCity suggestionCity = suggestionCityList.get(i);
                    sugs += "" + suggestionCity.getCityName();
                }
            }

            String pios = "";
            if (poiItemList != null && poiItemList.size() > 0) {
                List<CompanyBean> companyBeanList = new ArrayList<>();
                for (int i = 0; i < poiItemList.size(); i++) {
                    PoiItem poiItem = poiItemList.get(i);
                    CompanyBean bean = new CompanyBean();
                    bean.setAddress(poiItem.getAdName() + poiItem.getTitle());
                    bean.setArea(poiItem.getDirection());
                    bean.setProvince(poiItem.getProvinceName());
                    bean.setCity(poiItem.getCityName());
                    bean.setLatitude(String.valueOf(poiItem.getLatLonPoint().getLatitude()));
                    bean.setLongitude(String.valueOf(poiItem.getLatLonPoint().getLongitude()));
                    companyBeanList.add(bean);
                   // pios += "" + poiItem.getAdName() + poiItem.getLatLonPoint().getLatitude();
                }
                adapter.setNewData(companyBeanList);
                adapter.loadMoreComplete();
                adapter.setEnableLoadMore(true);
            }
            //tvResult.setText("rcode=" + rcode + ",poiResult=" + poiResult.toString() + ",sugs=" + sugs + ",pios="+pios);
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int rcode) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermiss = true;
        startLocation();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {
        showToast("好伤心，您将无法使用定位等相关功能");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }
}